//
//  LXAddSignViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/7/9.
//  Copyright © 2022 LX_App. All rights reserved.
//

#import "LXAddSignViewController.h"
#import "LXAppointmentedCell.h"
#import "LXSignContractModel.h"
#import "LXSignContractApplyViewController.h"
#import "LXSignRecordViewController.h"
@interface LXAddSignViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic) UIView *topView;
@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSInteger page;
@property (nonatomic) UIButton *dateBtn;
@property (nonatomic) NSString *searchText;
@property (nonatomic) NSString *appointTime;
@property (nonatomic) UILabel *signTotalLab;
@end

@implementation LXAddSignViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (kUserDefaultForBool(kRefreshStr)) {
        kUserDefaultSetBool(NO, kRefreshStr);
        [self.tableView.mj_header beginRefreshing];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self layoutCustomNav:self.view title:@"新增签约"];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#FAFBFC"];
    
    self.appointTime = [NSString getNowDateWithFormat:@"yyyy-MM-dd"];
    
    [self layoutTopView];
    
    self.data = [NSMutableArray array];
    
    [self.view addSubview:self.tableView];
    
    [self loadData];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self loadData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        self.page++;
        [self loadData];
    }];
    
}

-(void)loadData{

    // status  1  已预约
    NSMutableDictionary *dic = @{
        @"page":@(self.page),
        @"rows":@(10),
        @"status":[NSString stringWithFormat:@"%@",@(1)],
        @"appointDate":self.appointTime,
        @"suggest":@"1", // 好车推荐
    }.mutableCopy;
    if (!StringIsEmpty(self.searchText)) {
        [dic setValue:self.searchText forKey:@"searchKey"];
    }
    
   
    [MSNetworkManager getRevertUrl:[DOMAIN_URL stringByAppendingString:GET_GetTappointmentPage] params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        [self endRefreshing];
        
        if (isSuccess) {
            if (self.page == 1 || [self.tableView.mj_header isRefreshing]) {
                [self.data removeAllObjects];
                self.tableView.mj_header.state = MJRefreshStateIdle;
                [self.tableView.mj_footer resetNoMoreData];
            }
           
            NSArray *array = resonseObj[@"records"];
           
            [self.data addObjectsFromArray:[LXSignContractModel mj_objectArrayWithKeyValuesArray:array]];

            if (array.count < 1) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self isHaveEmptyData];
            [self.tableView reloadData];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self isHaveEmptyData];
        [self endRefreshing];
    } withShowHud:YES];
    
    
    NSString *url = [DOMAIN_URL stringByAppendingFormat:SigncontractPage_URL];
    [MSNetworkManager getRevertUrl:url params:@{@"page":@(1),@"rows":@(10)} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
            NSString *total = [NSString stringWithFormat:@"%@",resonseObj[@"total"]];
            self.signTotalLab.text = [NSString stringWithFormat:@"%@\n签约记录",total];
            [self.signTotalLab addAttributes:TextAttrCorlor(mainColor) forText:total size:[UIFont systemFontOfSize:26 weight:UIFontWeightSemibold]];

        }
        
    
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:NO];
    
}
-(void)layoutTopView{
    

    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, 200)];
    self.topView = topView;
    [self.view addSubview:topView];
    
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 15, ScreenWidth/2 - 10, 70)];
    [view1 addCorner:3];
    view1.backgroundColor = UIColor.whiteColor;
    [topView addSubview:view1];
    // 创建新签约
    [view1 whenTapped:^{
        LXSignContractApplyViewController *vc = [[LXSignContractApplyViewController alloc] init];
        vc.type = 1;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    
    UILabel *addLab = [[UILabel alloc] initWithFrame:CGRectMake((view1.width-28)/2, 10, 28, 28)];
    addLab.text = @"+";
    addLab.textAlignment = NSTextAlignmentCenter;
    addLab.font = [UIFont systemFontOfSize:28];
    addLab.textColor = mainColor;
    [addLab addCorner:2];
    [addLab setBackgroundColor:[mainColor colorWithAlphaComponent:0.1]];
    [view1 addSubview:addLab];
    
    
    UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(0, addLab.Y_height + 5, view1.width, 18)];
    lab1.textAlignment = NSTextAlignmentCenter;
    lab1.text = @"创建新签约";
    lab1.font = [UIFont systemFontOfSize:14];
    lab1.textColor = Color333;
    [view1 addSubview:lab1];
    
    

    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(view1.X_width + 10, 15, ScreenWidth/2 - 20, 70)];
    [view2 addCorner:3];
    view2.backgroundColor = UIColor.whiteColor;
    [topView addSubview:view2];
    // 签约记录
    [view2 whenTapped:^{
        LXSignRecordViewController *vc = [[LXSignRecordViewController alloc] init];
        [self pushToNextController:vc];
    }];
    
    
    UILabel *signTotalLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, view1.width, 50)];
    signTotalLab.textAlignment = NSTextAlignmentCenter;
    signTotalLab.numberOfLines = 2;
    signTotalLab.text = @"0\n签约记录";
    signTotalLab.lineSpace = 5;
    signTotalLab.font = [UIFont systemFontOfSize:14];
    signTotalLab.textColor = Color333;
    [view2 addSubview:signTotalLab];
    self.signTotalLab = signTotalLab;
    [signTotalLab addAttributes:TextAttrCorlor(mainColor) forText:@"0" size:[UIFont systemFontOfSize:26 weight:UIFontWeightSemibold]];
    
    
    LXTopSearchView *searchView = [[LXTopSearchView alloc] initWithFrame:CGRectMake(0,view2.Y_height + 5, kScreenWidth, 70)];
    searchView.textField.placeholder = @"输入关键词进行搜索";
    searchView.textField.width = searchView.width - 80;
    searchView.searchBtn.frame = CGRectMake(MaxX(searchView.textField)+12, searchView.textField.top, kScreenWidth-MaxX(searchView.textField)-24, searchView.textField.height);
//    self.searchView = searchView;
    [searchView.searchBtn setTitleColor:Color333 forState:UIControlStateNormal];
    [searchView.searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    searchView.topView.backgroundColor = self.view.backgroundColor;
    [searchView.searchBtn whenTapped:^{
        [self.view endEditing:YES];
        [self.tableView.mj_header beginRefreshing];
    }];
    [topView addSubview:searchView];
    // 输入
    [searchView setChangeTextFieldBlock:^(NSString * _Nonnull text) {
        self.searchText = text;
    }];
    
    
    UILabel *lab3 = [[UILabel alloc] initWithFrame:CGRectMake(10, searchView.Y_height + 10, 150, 18)];
    lab3.textAlignment = NSTextAlignmentLeft;
    lab3.text = @"已预约列表";
    lab3.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    lab3.textColor = Color333;
    [topView addSubview:lab3];
    
    
    
    UIButton *dateBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 100, searchView.Y_height + 10, 90, 20)];
    [dateBtn setTitle:[NSString getNowDateWithFormat:@"yyyy-MM-dd"] forState:UIControlStateNormal];
    [dateBtn setTitleColor:Color333 forState:UIControlStateNormal];
    [dateBtn setImage:Image(@"acc_down") forState:UIControlStateNormal];
    dateBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [dateBtn setIconInRightWithSpacing:3];
    [topView addSubview:dateBtn];
    self.dateBtn = dateBtn;
    [dateBtn addTarget:self action:@selector(clickDateAction) forControlEvents:UIControlEventTouchUpInside];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LXSignContractModel *model = self.data[indexPath.section];
    
    LXAppointmentedCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXAppointmentedCell class]) forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.model = model;
    
    [cell.btn1 whenTapped:^{
       
        NSDictionary *dic = @{@"id":model.ID};
        [MSNetworkManager getRevertUrl:[DOMAIN_URL stringByAppendingString:GET_GetTappointmentById] params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if(isSuccess){
                
                LXSignContractModel *mm = [LXSignContractModel mj_objectWithKeyValues:resonseObj[@"appointment"]];
                
                mm.signCarBrand = model.carBrand;
                mm.signModel  = model.carMode;
                mm.appointmentId = model.ID;
                mm.carModel = mm.carMode;
                mm.driverId = mm.cdUserId;
                mm.driverName = !StringIsEmpty(mm.dname)?mm.dname:mm.nickname;
                mm.driverPhone = mm.userPhone;
                LXSignContractApplyViewController *vc = [[LXSignContractApplyViewController alloc] init];
                vc.type = 2;
                vc.signContractModel = mm;
                [self pushToNextController:vc];
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
          
        } withShowHud:YES];
        
        
       
        
        
    }];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    vv.backgroundColor = self.view.backgroundColor;
    return vv;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.Y_height + 5, ScreenWidth, kScreenHeight - self.topView.Y_height - 15) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 10;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#FAFBFC"];
        _tableView.rowHeight = 65;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXAppointmentedCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXAppointmentedCell class])];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}
- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
- (void)isHaveEmptyData{
    if (self.data.count == 0) {
        self.tableView.startTip = YES;
        self.tableView.tipView.backgroundColor = self.tableView.backgroundColor;
        self.tableView.tipImage = [UIImage imageNamed:@"No_order_icon"];
        self.tableView.tipView.hidden = NO;
        self.tableView.scrollEnabled = YES;
    }else{
        self.tableView.tipView.hidden = YES;
        self.tableView.scrollEnabled = YES;
    }
}
-(void)clickDateAction{
    
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.dateBtn.titleLabel.text withIsMaxDate:YES withNoForward:NO WithTips:@"请选择预约日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    
    datePicker.block = ^(NSString *yearString){
        
        [self.dateBtn setTitle:yearString forState:UIControlStateNormal];
        self.appointTime = yearString;
        [self.tableView.mj_header beginRefreshing];
    };
    
}
@end
